package com.plian.system.controller.transfer;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.system.config.AppKeySign;
import com.plian.system.dto.transfer.DataPlatSign;
import com.plian.system.entity.fr.bank.BankKey;
import com.plian.system.entity.sys.Org;
import com.plian.system.model.R;
import com.plian.system.model.token.PassToken;
import com.plian.system.service.fr.bank.IBankKeyService;
import com.plian.system.service.sys.orgzation.IOrgService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: Take-off
 * @Description: TODO 组织数据 输出
 * @Date: 2022/11/8 10:20 AM
 * @Version: 1.0
 **/
@RestController
@RequestMapping("api/orgTransfer")
@AllArgsConstructor
@Api(value = "组织数据-输出", tags = "组织数据输出")
@Slf4j
public class OrgzationTransferController {

    private IBankKeyService bankKeyService;

    private IOrgService orgService;

    /**
     * 提供所有数据接口
     * @param dataPlatSign
     */
    @PostMapping(value = "/init")
    @PassToken
    @AppKeySign
    public R initOrg(@RequestBody DataPlatSign dataPlatSign){
        log.debug("toklen:" + dataPlatSign.getToken());
        String appId = dataPlatSign.getAppId();
        BankKey bankKey = bankKeyService.getOne(Wrappers.<BankKey>lambdaQuery().eq(BankKey::getAppId, appId));
        String topGroupId = bankKey.getTopGroupId();
        List<Org> allChild = orgService.getAllChild(topGroupId);
        return R.data(allChild);
    }

    /**
     * 提供时间段内的组织-数据接口
     * @param dataPlatSign
     */
    @PostMapping(value = "/org-time")
    @PassToken
    @AppKeySign
    public R orgByTime(@RequestBody DataPlatSign dataPlatSign){
        log.debug("toklen:" + dataPlatSign.getToken());
        String appId = dataPlatSign.getAppId();
        BankKey bankKey = bankKeyService.getOne(Wrappers.<BankKey>lambdaQuery().eq(BankKey::getAppId, appId));
        String topGroupId = bankKey.getTopGroupId();
        List<Org> allChild = orgService.getAllChild(topGroupId);
        if (Optional.ofNullable(dataPlatSign.getEndTime()).isPresent()){
            allChild = allChild.stream().filter(org -> Optional.ofNullable(org.getUpdateTime()).isPresent() &&
                    (dataPlatSign.getStartTime().compareTo(org.getUpdateTime()) < 1 && dataPlatSign.getEndTime().compareTo(org.getUpdateTime()) > -1)).collect(Collectors.toList());
        }
        return R.data(allChild);
    }
}
